package com.example.loader;

import com.hazelcast.core.HazelcastInstance;
import org.springframework.stereotype.Service;

import javax.cache.Cache;
import javax.cache.CacheManager;
import javax.cache.Caching;
import javax.cache.configuration.MutableConfiguration;
import javax.cache.expiry.Duration;
import javax.cache.expiry.TouchedExpiryPolicy;
import java.util.concurrent.TimeUnit;

/*
 * @className: HazelcastCacheManagerLoader
 * @author: chentao
 * @date: 2025/2/19 上午8:30
 * @Version: 1.0
 * @description:
 */
@Service
public class HazelcastCacheLoader implements HazelcastLoader {

    private static final String USER_CACHE_NAME_KEY = "USER_CACHE_NAME";

    private Cache<String, String> cache = null;

    @Override
    public void init(HazelcastInstance hazelcastInstance) throws Exception {
        CacheManager cacheManager = Caching.getCachingProvider().getCacheManager();
        MutableConfiguration mutableConfiguration = new MutableConfiguration<String, String>();
        mutableConfiguration.setTypes(String.class, String.class);
        mutableConfiguration.setExpiryPolicyFactory(TouchedExpiryPolicy.factoryOf(new Duration(TimeUnit.SECONDS, 10)));
        if (cacheManager.getCache(USER_CACHE_NAME_KEY) == null) {
            this.cache = cacheManager.createCache(USER_CACHE_NAME_KEY, mutableConfiguration);
        } else {
            this.cache = cacheManager.getCache(USER_CACHE_NAME_KEY);
        }
    }

    //对外暴露接口
    public Cache<String, String> getCache() {
        return cache;
    }
}
